package dejur.projectutil;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.MappingException;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.SQLServerDialect;

public class ScriptGenerator {

	public static void main(String[] args) throws MappingException,
			ClassNotFoundException, IOException {

		Configuration config = new Configuration();

		File modelsFolder = new File(
				"C:/Projetos/DEJUR/DEJUR_WEB/app/models");
		File[] entities = modelsFolder.listFiles();
		for (int i = 0; i < entities.length; i++) {
			File entityJavaFile = entities[i];
			String entity = entityJavaFile.toString();
			if (entity.endsWith(".java")) {

				entity = StringUtils.substringBeforeLast(
						StringUtils.substringAfterLast(
								entityJavaFile.toString(), "\\"), ".");
				Class<?> clazz = Class.forName("models." + entity);
				config.addAnnotatedClass(clazz);
			}
		}
		config.setProperty("hibernate.dialect",
				"org.hibernate.dialect.SQLServerDialect");
		config.buildSessionFactory();
		String[] schema = config
				.generateSchemaCreationScript(new SQLServerDialect());

		StringBuilder sql = new StringBuilder();
		for (int i = 0; i < schema.length; i++) {
			String line = schema[i];
			sql.append(line + ";" + System.getProperty("line.separator"));
			System.out.println(line + ";");
		}
		
		FileUtils.writeStringToFile(new File(
				"C:/Projetos/DEJUR/DEJUR_WEB/docs/script.sql"), sql.toString());
	}
}
